import json
from crawler.extractors import JsonpExtractor
from crawler.fields import ContainerField, JsonField

#
__all__ = ['SsenseMainExtractor', 'SsenseDetailExtractor']


class SsenseMainInfoExtractor(JsonpExtractor):
    container = ContainerField(json_selector='$.products.all[*]')
    url = JsonField(json_selector='$.url')
    spu_id = JsonField(json_selector='$.id')
    title = JsonField(json_selector='$.name.zh')
    gender = JsonField(json_selector='$.gender')
    brand = JsonField(json_selector='$.brand.name.zh')
    currency = JsonField(json_selector='$.priceByCountry[0].currency')
    cost_price = JsonField(json_selector='$.priceByCountry[0].formattedLowest.amount')
    retail_price = JsonField(json_selector='$.priceByCountry[0].formattedPrice')


class SsenseDetailInfoExtractor(JsonpExtractor):
    atlas_list = JsonField(json_selector='$.products.current.images[*]', many=True)
    composition = JsonField(json_selector='$.products.current.composition')
    product_des = JsonField(json_selector='$.products.current.description')
    # color = JsonField(json_selector='$.products.current.primaryColor.en')


class SsenseSizeStockDetailInfoExtractor(JsonpExtractor):
    container = ContainerField(json_selector='$.products.current.variants[*]')
    # 是否有库存的判断 False True
    in_stock = JsonField(json_selector='$.inStock')
    low_stock = JsonField(json_selector='$.lowStock')
    size = JsonField(json_selector='$.size.name')


class SsenseMainExtractor:
    @classmethod
    def get_item(cls, response, res):
        return cls._extract(response, res)

    @classmethod
    def _extract(cls, response, res):
        task = response.meta['task']
        info_list = list()
        for item in SsenseMainInfoExtractor.get_items(response, res):
            info_dict = dict()
            info_dict['spu_id'] = item.spu_id
            info_dict['title'] = item.title
            # 品牌
            info_dict['brand'] = item.brand
            # 性别
            info_dict['sex'] = item.gender
            # 图集 需要请求详情页
            info_dict['atlas'] = ''
            # 公价
            info_dict['retail_price'] = item.retail_price.split('$')[1] if item.retail_price else ''
            # 成本价 原价对应公价
            info_dict['cost_price'] = item.cost_price.split('$')[1] if item.cost_price else info_dict['retail_price']

            info_dict['url'] = 'https://www.ssense.com/en-hk' + item.url
            # 规格 ，
            info_dict['specifications'] = ''
            # 颜色
            info_dict['color'] = ''
            info_dict['category'] = task['info']['category']
            info_dict['composition'] = ''
            info_dict['currency'] = 'USD'
            # 商品描述。详情页的
            info_dict['product_des'] = ''
            info_dict['size_stock'] = ''
            info_list.append(info_dict)

        return info_list


#
class SsenseDetailExtractor:
    @classmethod
    def get_item(cls, response, resp):
        return cls._extract(response, resp)

    @classmethod
    def _extract(cls, response, resp):
        other_item = SsenseDetailInfoExtractor.get_item(response, resp)
        atlas_list = [
            'https://cldny-ssense.ccedge.cn/image/upload/b_white,c_lpad,g_center,h_1412,w_940/c_scale,h_960/f_auto,dpr_2.0/' +
            _.split('/')[-1] for _ in other_item.atlas_list]
        composition = other_item.composition.get('en').replace('.', '')
        product_des = other_item.product_des.get('en')
        color = other_item.product_des.get('en').split('Supplier color:')[1].strip()
        stock_size_list = list()
        for item in SsenseSizeStockDetailInfoExtractor.get_items(response, resp):
            info_dict = dict()
            in_stock = item.in_stock
            low_stock = item.low_stock
            if in_stock:
                if not low_stock:
                    stock = 10
                else:
                    stock = item.low_stock
            else:
                continue

            if 'UNI' in item.size:
                try:
                    info_dict['size'] = product_des.split('Size:')[1].split('Supplier color')[0].strip()
                except:
                    info_dict['size'] = "UNI"
            else:
                info_dict['size'] = item.size
            info_dict['stock'] = stock
            stock_size_list.append(info_dict)

        return stock_size_list, atlas_list, composition, product_des, color
